<template>
  <div class="c-bg-sgray">
    <template v-if="!bookingInfoOnly">
      <div>
        <my-small-tabbar class="c-bg-white" :tabList="bookingTypeList" :tabIndex="typeBar" @changeTab="changeBookingType"></my-small-tabbar>
      </div>
      <div v-show="typeBar == 1" class="c-pt24 c-ph24">
        <div v-for="(item, index) in schedulingList" :key="index" class="c-pt28 c-bg-white c-br20 c-mb24">
          <div class="c-ph24 c-flex-row c-pb40 c-bd-b1">
            <img class="c-ww80 c-hh80 c-br40 c-flex-shrink0 c-mr32" :src="$addXossFilter(item.headimg, require('../../../assets/defult_head.png'))" alt="">
            <div class="c-w0 c-flex-grow1 c-flex-column c-justify-sb">
              <div class="c-flex-row c-aligni-end">
                <span class="c-fs24 c-fc-xblack c-text-ellipsis1" :class="item.title ? 'c-maxw300' : 'c-w100'">{{item.name}}</span>
                <span class="c-fs20 c-fc-sblack c-w0 c-flex-grow1 c-ml12 c-text-ellipsis1">{{item.title}}</span>
              </div>
              <div class="c-fs20">
                <span class="theme-fc">实付：{{'￥' | iosPriceFilter}}{{item.price}}</span><span class="c-ph16 c-fs24 c-fc-gray">|</span><span class="c-fc-gray">{{item.status == 1 ? '上架中' : '已下架'}}</span>
              </div>
            </div>
          </div>
          <div class="c-flex-row c-justify-sb">
            <div @click="goStudentList(item.atId)" class="c-hh80 c-fs24 c-fc-xblack c-flex-1 c-flex-row c-flex-center c-bd-r1">学员预约</div>
            <div @click="goMyScheduling(item.atId)" class="c-hh80 c-fs24 c-fc-xblack c-flex-1 c-flex-row c-flex-center">排班情况</div>
          </div>
        </div>
        <loading-status-tem :dataStatus="schedulingDataStatus" noDataText="暂无相关预约"></loading-status-tem>
      </div>
    </template>
    <div v-show="typeBar == 2 || bookingInfoOnly">
      <div v-if="!bookingInfoOnly" class="c-w100 c-pz100 c-maxw640">
        <div class="c-bg-white c-flex-row c-pt15 c-pb20">
          <div class="c-flex-row c-content-auto c-mh24 c-hh48">
            <div v-for="(item) in tabList" :key="item.index" @click="changeType(item.index)" :class="type == item.index ? 'theme-bg-10 theme-bd1-20 theme-fc' : 'c-bg-f2 c-fc-gray'" class="c-boxSizing-b c-flex-row c-flex-center c-flex-shrink0 c-mr20 c-ww120 c-hh44 c-br30 c-fs24">{{item.title}}</div>
          </div>
        </div>
      </div>
      <my-small-tabbar v-else class="c-bg-white" :tabList="tabList" :tabIndex="type" @changeTab="changeType"></my-small-tabbar>
      <div class="c-ph24 c-pt24" v-show="dataInfo.length > 0">
        <div class="c-p c-mb24 c-bg-white c-br12 c-fs24 c-ph24 c-pv24" v-for="(item,index) in dataInfo" :key="index">
          <div class="c-flex-row c-justify-sb c-fc-gray c-bd-b1 c-pb10" v-if="item.status == -2">
            <span>{{item.refundAt}}</span>
            <span>退款成功</span>
          </div>
          <div class="c-flex-row c-mt16">
            <img class="c-hh80 c-ww80 c-brp50 c-center imgCloseBig c-mr10" :src="$addXossFilter(item.headimg, require('../../../assets/defult_head.png'))" />
            <div class="c-flex-column c-justify-sb c-pl20 c-w0 c-flex-grow1 c-fc-sblack">
              <div class="c-fs20 c-mb12 c-flex-row c-aligni-end c-text-ellipsis2 c-fc-xblack">
                <span class="c-fs24 c-mr10">{{item.name}}</span>
                <span>{{item.title}}</span>
              </div>
              <div class="c-fs24 c-mb12 theme-fc" v-if="item.payMoney != 0 && item.payMoney != null"><span>实付：</span><span>{{'￥' | iosPriceFilter}}{{Number(item.payMoney).toFixed(2)}}</span></div>
              <div class="c-fs24 c-mb12 theme-fc" v-else>免费</div>
              <div class="c-fc-gray c-mb12 c-fs18"><span>预约时间：</span>{{item.date}}  {{item.startAt}}-{{item.endAt}} </div>
              <div class="c-fc-gray c-fs18"><span>咨询模式：</span>{{item.consumptionPattern == 1 ? "面对面咨询" : item.consumptionPattern == 2 ? "视频咨询" : item.consumptionPattern == 3 ? "电话咨询" : "线上连麦咨询"}}</div>
            </div>
          </div>
          <div class="c-flex-row c-aligni-center c-justify-end c-mt24 c-pt24 c-bd-t1-f6 c-fs22">
            <!-- 预约直播 && 直播状态还没结束 && 预约状态为未开始 || 已完成 || 已过期 -->
            <template v-if="item.liveId && item.liveStatus < 2 && (item.status == 1 || item.status == 2 || item.status == -3)">
              <div v-if="userListType == 2" @click="clickShowLiveQrcode(item.atmId)" class="theme-bg c-ww120 c-hh48 c-lh48 c-br24 c-textAlign-c c-fc-white">开始咨询</div>
              <div v-if="userListType == 1" class="c-ww120" >
                <wxOpenWeapp path="yuyue/pages/scanCodeStu/index" :pathQuety="item.wxappQuery">
                  <div class="theme-bg c-ww120 c-hh48 c-lh48 c-br24 c-textAlign-c c-fc-white">开始咨询</div>
                </wxOpenWeapp>
              </div>
            </template>
            <!-- 预约直播已结束 && 结束时间再半小时以内，才可以重新开启 -->
            <div @click="clickRestartBook(item.liveId)" v-if="userListType == 2 && item.liveId && item.liveStatus == 2 && item.liveIsReOpen == 1 && (item.status == 1 || item.status == 2 || item.status == -3)" class="theme-bg c-ww188 c-hh48 c-lh48 c-br24 c-textAlign-c c-fc-white">重新开始咨询</div>
            <div v-if="userListType == 2 && type == 2" class="c-bd1-ccc c-ww120 c-hh48 c-lh48 c-br24 c-textAlign-c c-fc-xblack c-ml10" @click="uploadSummarize(item.aeId)">总结</div>
            <div class="c-bd1-ccc c-ww120 c-hh48 c-lh48 c-br24 c-textAlign-c c-fc-xblack c-ml10" @click="getDetail(index)">查看更多</div>
            <div v-if="(userListType == 2 && (type==1 || type==-3)) || (userListType == 1 && type==1 && cancelBtnSetting)" class="c-bd1-ccc c-ww120 c-hh48 c-lh48 c-br24 c-textAlign-c c-fc-xblack c-ml10" @click="cancelBookingShow(item.aeId)">取消预约</div>
            <div v-if="userListType==2&&(type==1||type==-3)" class="theme-bg c-ww120 c-hh48 c-lh48 c-br24 c-textAlign-c c-fc-white c-ml10" @click="sureBookingShow(item.aeId)">确认消费</div>
            <div v-if="item.status == 2 && !item.isComment && item.tStatus == 1&&userListType==1" class="theme-bg c-ww120 c-hh48 c-lh48 c-br24 c-textAlign-c c-fc-white c-ml10" @click="goComment(item)">去评价</div>
          </div>
        </div>
        <div v-transfer-dom>
          <popup v-model="showDetail" class="c-br-tr20 c-br-tl20 c-pv16 c-bg-white" @on-hide="onHide">
            <div class="c-bg-white c-fs24">
              <div class="c-bd-b1 c-pv20 c-p c-textAlign-c">
                <div class="c-fs30">价格明细</div>
                <span class="iconfont c-pa c-p-r24 c-p-t24 c-fs24 c-fc-gray" @click="closeDetail">&#xe61b;</span>
              </div>
              <div class="c-contexty-scroll c-maxh500" ref="box">
                <div class="c-ph24 c-bd-b1 c-flex-row c-justify-sb c-pv30">
                  <span class="c-fc-sblack">消费总价</span>
                  <span>{{'￥' | iosPriceFilter}}{{Number(detailInfo.price).toFixed(2)}}</span>
                </div>
                <div class="c-ph24 c-flex-row c-justify-sb c-pv30">
                  <span class="c-fc-sblack">预约金</span>
                  <span>{{'￥' | iosPriceFilter}}{{Number(detailInfo.deposit).toFixed(2)}}</span>
                </div>
                <div class="c-ph24 c-flex-row c-justify-sb c-pb30" v-if="detailInfo.discount != '' && detailInfo.discount != 100">
                  <span class="c-fc-sblack">身份折扣</span>
                  <span v-if="detailInfo.discount == 0">免费</span>
                  <span v-else>{{Number(detailInfo.discount).toFixed(2) / 10}}折</span>
                </div>
                <div class="c-ph24 c-flex-row c-justify-sb c-pb30" v-if="detailInfo.deductedPointMoney != 0 && detailInfo.deductedPointMoney != null">
                  <span class="c-fc-sblack">{{customPointName}}抵扣</span>
                  <span>-{{'￥' | iosPriceFilter}}{{Number(detailInfo.deductedPointMoney).toFixed(2)}}</span>
                </div>
                <div class="c-ph24 c-flex-row c-justify-sb c-pb30" v-if="detailInfo.useCoupon &&detailInfo.useCoupon != -1">
                  <span class="c-fc-sblack">优惠券抵扣</span>
                  <span>-{{'￥' | iosPriceFilter}}{{Number(detailInfo.deductedCouponMoney).toFixed(2)}}</span>
                </div>
                <div class="c-ph24 c-bd-b1 c-flex-row c-justify-sb c-pb30">
                  <span class="c-fc-sblack">预约金实付</span>
                  <span class="theme-fc c-fw-b">{{'￥' | iosPriceFilter}}{{Number(detailInfo.payMoney).toFixed(2)}}</span>
                </div>
                <div class="c-ph24 c-bd-b1 c-flex-row c-justify-sb c-pv30" v-if="detailInfo.enrollName">
                  <span class="c-fc-sblack c-ww160">姓名</span>
                  <span>{{detailInfo.enrollName}}</span>
                </div>
                <div class="c-ph24 c-bd-b1 c-flex-row c-justify-sb c-pv30" v-if="detailInfo.enrollMobile">
                  <span class="c-fc-sblack c-ww160">手机号</span>
                  <span>{{detailInfo.enrollMobile}}</span>
                </div>
                <div class="c-ph24 c-bd-b1 c-flex-row c-justify-sb c-pv30" v-if="detailInfo.wxNumber">
                  <span class="c-fc-sblack c-ww160">微信号</span>
                  <span>{{detailInfo.wxNumber}}</span>
                </div>
                <div v-for="(item, index) in detailInfo.fieldVal" :key="index" v-if="detailInfo.fieldVal.length!=0">
                  <div class="c-ph24 c-bd-b1 c-flex-row c-justify-sb c-pv30" v-if="item.value&&item.value!=''">
                    <span class="c-fc-sblack c-ww160">{{item.name}}</span>
                    <span>{{item.value}}</span>
                  </div>
                </div>
                <div class="c-ph24 c-bd-b1 c-flex-row c-justify-sb c-pv30" v-if="detailInfo.consumptionPattern == 1&&detailInfo.address!=''">
                  <span class="c-fc-sblack c-ww160">预约地址</span>
                  <span>{{detailInfo.address}}</span>
                </div>
                <div class="c-ph24 c-pv30 c-fc-sblack" v-if="detailInfo.instructions != null && detailInfo.instructions != ''">
                  <div class="c-mb10">预约说明</div>
                  <div>{{detailInfo.instructions}}</div>
                </div>
                <div class="c-ph24 c-pv30 c-fc-sblack" v-if="detailInfo.remark && detailInfo.remark.length > 0">
                  <div class="c-mb10">备注</div>
                  <div v-for="(item,index) in detailInfo.remark" :key="index">
                    <div class="tinymce-text c-wb-ba c-contexty-scroll" :class="[cfg.isCopyPicture == 0 ? 'closeBig' : 'aCloseBig', cfg.isCopy == 0 ? 'copyNot' : '']" v-html="item.content"></div>
                  </div>
                </div>
              </div>
            </div>
          </popup>
        </div>
        <open-modal :openModal="showComment" @closeModal="hideComment">
          <div class="c-bg-white c-br-tl32 c-br-tr32 c-text-hidden c-maxw640 c-pb20 c-p c-pz1000">
            <div class="c-fs28 c-fw-b c-textAlign-c c-pv36">发表评价</div>
            <div @click="showComment = false" class="c-fs28 c-fc-gray iconfont c-p-t40 c-p-r24 c-pa">&#xe84e;</div>
            <div class="c-contexty-scroll c-pb80">
              <div class="c-ph24 c-pb48 c-fs28">
                <div class="c-flex-row c-aligni-center c-justify-sb c-mb40">
                  <span class="c-fc-xblack c-fw-b">服务评分</span>
                  <rater-com v-model="rate" star="<span class='iconfont c-fs30'>&#xe8c7;</span>" fontSize="20" active-color="#FAAD14"></rater-com>
                </div>
                <div class="c-flex-row c-flexw-wrap c-aligni-center c-mr-24 c-pb30 c-pt20" v-if="rate != 0 && goodTemplates && goodTemplates.length > 0">
                  <div v-if="rate == 5" v-for="(item,index) in goodTemplates" :key="item.ctId" class="c-hh60 c-lh60 c-ph30 c-br30 time-list c-mb24 c-mr24"
                    :class="item.isChoosed == true ? 'theme-back c-fc-white' : 'c-fc-sblack'" @click="chooseTag(item.content,index,item.isChoosed,1)">{{item.content}}</div>
                  <div v-if="rate != 5 && rate > 0" v-for="(item,index) in badTemplates" :key="item.ctId" class="c-hh60 c-lh60 c-ph30 c-br30 time-list c-mb24 c-mr24"
                    :class="item.isChoosed == true ? 'theme-back c-fc-white' : 'c-fc-sblack'" @click="chooseTag(item.content,index,item.isChoosed,2)">{{item.content}}</div>
                </div>
                <textarea v-model="commentText" @focus='inputFocus' @blur='inputBlur' name="" id="inputArea" cols="20" rows="5" placeholder="请在此写出你的评论内容"
                  class="c-fs24 c-fc-xblack c-lh40 c-w100 c-hh260 c-bd0 c-ph24 c-pv24 c-br12 c-wb-ba textarea c-fc-xblack"></textarea>
              </div>
              <div class="c-w100 c-maxw640 c-hh120 c-bg-white c-pv18 c-pf c-p-b0 c-ph24">
                <div class="c-textAlign-c c-mb40 c-w100 c-br32 c-m-0auto c-bd0 c-fs28 c-hh72 c-lh72 c-ph24 c-lh c-br36 theme-bg c-fc-white" @click="submitComment">立即发布</div>
              </div>
            </div>
          </div>
        </open-modal>
      </div>
      <loading-status-tem :dataStatus="dataStatus" noDataText="暂无相关预约"></loading-status-tem>
    </div>
    <!-- 取消预约 -->
    <div v-show="cancelBookingFalg" class="c-pz1002 c-w100 c-h c-pf c-p-l0 c-p-t0 c-flex-row c-flex-center">
      <div class="c-translucent-balck50 c-text-hidden c-pz-1 c-w100 c-h c-pa c-p-l0 c-p-t0" @click="cancelBookingFalg = false;" data-type='cancel'></div>
      <div class="c-ww540 c-bg-white c-flex-column c-pz1 c-br20">
        <div class="c-fs28 c-textAlign-c c-pt50 c-fw-b c-lh c-pb30">提示</div>
        <div :class="userListType == 1 ? 'c-textAlign-c' : ''" class="c-ph30 c-fs24">
          {{userListType == 1 ? '确定取消该预约吗？' : '取消预约后，如用户有交预约定金，将退回给用户，确定取消该预约吗？'}}
          <div class="c-hh50 c-lh50 c-fs18 c-textAlign-l c-fc-red"></div>
        </div>
        <footer class="c-fs20 c-flex-row c-fs28 c-bd-t1">
          <div @click="cancelBookingFalg = false;" class="c-hh88 c-flex-row c-flex-center c-flex-grow1 c-w0 c-fc-gray c-bd-r1">取消</div>
          <div @click="cancelBooking" class="c-hh88 c-flex-row c-flex-center c-flex-grow1 c-w0 theme-fc">确定</div>
        </footer>
      </div>
    </div>
    <!-- 确认预约 -->
    <div v-show="sureBookingShowFalg" class="c-pz1002 c-w100 c-h c-pf c-p-l0 c-p-t0 c-flex-row c-flex-center">
      <div class="c-translucent-balck50 c-text-hidden c-pz-1 c-w100 c-h c-pa c-p-l0 c-p-t0" @click="sureBookingShowFalg = false;" data-type='cancel'></div>
      <div class="c-ww540 c-bg-white c-flex-column c-pz1 c-br20">
        <div class="c-fs28 c-textAlign-c c-pt50 c-fw-b c-lh c-pb30">提示</div>
        <div class="c-ph30 c-fs24">
          该客户确认已消费？
          <div class="c-w100 c-fs20 c-lh64 c-br10 c-bd1 c-mt10" v-if="type==-3">
            <group class="c-w100 placeholder-gray sureTime">
              <datetime :themeColor="$getThemeColor()" title="" :readonly="readonly" placeholder="请选择消费时间" v-model="sureTime" @on-change="changeBirthday"></datetime>
            </group>
          </div>
          <div class="c-hh50 c-lh50 c-fs18 c-textAlign-l c-fc-red"></div>
        </div>
        <footer class="c-fs20 c-flex-row c-fs28 c-bd-t1">
          <div @click="sureBookingShowFalg = false;" class="c-hh88 c-flex-row c-flex-center c-flex-grow1 c-w0 c-fc-gray c-bd-r1">取消</div>
          <div @click="sureBooking" class="c-hh88 c-flex-row c-flex-center c-flex-grow1 c-w0 theme-fc">确定</div>
        </footer>
      </div>
    </div>
    <!-- 切换身份 -->
    <!-- <div @click="clickChangeRole" class="theme-bg c-fc-white changeRole c-ww120 c-pv12 c-textAlign-c c-fs20" v-if="identity== 2">切换{{ userListType == 2 ? "学员" : "教师" }}</div> -->
    <cj-popup v-model="showEnterPcTip" round closeable="true" close-icon-position="bottom-center" close-icon="icon-shanchu" class="c-ww460">
      <div class="invite-book-bg-img c-flex-column c-aligni-center c-p" v-if="showEnterPcTip">
        <div class="c-fs22 c-fc-gray c-pt220 c-pb16">点击下方按钮，进入小程序开始视频咨询</div>
        <section v-if="teacherWxappQuery" class="c-ww280 c-hh60">
          <wxOpenWeapp path="yuyue/pages/scanCodeTea/index" :pathQuety="teacherWxappQuery">
            <div class="c-ww280 c-hh60 c-flex-row c-flex-center c-fc-white c-fs24 c-br36 c-bg-xblue">进入小程序</div>
          </wxOpenWeapp>
        </section>
        <div class="c-pt76 c-ww400 c-pb20 c-fs22 c-fc-gray c-textAlign-c">
          点击下方按钮复制链接到浏览器打开(如需演示课件、共享屏幕等请选择此方式)
        </div>
        <div @click="copyText" class="c-ww280 c-hh60 c-flex-row c-flex-center c-fc-white c-fs24 c-br36 c-bg-xblue">复制链接</div>
      </div>
    </cj-popup>
    <open-modal class="c-pz10000" :needCloseBtn="true" :openModal='popUploadSummarize' @closeModal='popUploadSummarize = false'>
      <div class="c-bg-white c-pb30 c-pt40 c-br-tl20 c-br-tr20 c-p">
        <div class="c-fs28 c-fc-xblack c-fw600 c-textAlign-c c-ph24">总结</div>
        <div class="c-maxh600 c-content-scroll">
          <div class="c-mt30 c-bg-F6F7F9 c-ph20 c-pv20 c-br20 c-mh24">
            <textarea v-model="textContent" autofocus="autofocus" rows="5" placeholder="记录一下此次预约的总结或想法吧…" class="c-bd0 c-bg-F6F7F9 c-w100 c-fs24 c-lh40"></textarea>
            <div class="c-fs20 c-fc-gray c-textAlign-r">{{textContent.length}}/1000</div>
          </div>
          <div class="c-ph12 c-flex-row c-flexw-wrap c-mt30">
            <template v-if="uploadImgList && uploadImgList.length > 0">
              <div v-for="(item,index) in uploadImgList" :key="index" class="c-w33 c-ph12 c-mt20">
                <div class="c-hh180 c-br8 c-p">
                  <img class="c-w100 c-hh180 c-br8" @click="clickPreviewImage(item.url)" :src="$addXossFilter(item.url ,require('../../../assets/defult270.png'))" />
                  <div @click="delUploadImage(index)" class="iconfont c-fs18 c-fc-white c-ww32 c-hh32 c-br16 c-bg-gray c-flex-row c-flex-center c-pa c-p-t0 c-p-r0">&#xeca0;</div>
                </div>
              </div>
            </template>
            <div class="c-w33 c-ph12 c-mt20">
              <div @click="clickAnswerPic" class="c-hh180 c-br8 c-flex-column c-flex-center c-bd-d1 c-p">
                <div class="iconfont c-fs48 c-fc-gray">&#xe689;</div>
                <div class="c-fs20 c-fc-gray c-mt12">添加图片</div>
                <input class="c-pa c-opacity0 c-p-t0 c-p-l0 c-w100 c-hh180 c-fs10" v-if="!isWeiXin" ref="uploadImg" name="file" type="file" accept="image/*" @change="clickAnswerPic($event)" />
              </div>
            </div>
          </div>
          <div class="c-ph24 c-mt30 c-flex-row c-aligni-center c-justify-sb">
            <div class="c-fs24 c-fc-gray">最多上传5张图片</div>
            <div @click="submitSummary" class="c-ww180 c-hh56 theme-bg c-flex-row c-flex-center c-fc-white c-fs24 c-br28">提交</div>
          </div>
        </div>
      </div>
    </open-modal>
    <!--客服功能-->
    <custom-service-tmp :position="16"></custom-service-tmp>
  </div>
</template>

<script>
import loadingStatusTem from "@/components/templates/common/loadingStatusTem.vue";
import MySmallTabbar from "@/components/templates/common/MySmallTabbar.vue";
import wxOpenWeapp from '@/components/templates/common/wxOpenWeapp.vue';
import OpenModal from "@/components/templates/common/openModal.vue";
import CustomServiceTmp from "@/components/templates/custService/customServiceTmp.vue";
import raterCom from "@/components/templates/common/raterCom.vue";
import { utilJs, wxUtilJs } from "@/utils/common.js";
import { Popup, Datetime } from 'ckjrweb-mp-ui/src/components/index';
let clickFlag = true
const LIMIT = 20;
let page = 1;
let schedulingPage = 1;
let serverIdImgArr = []; //上传图片的serverID
let imgData = {};
let inputScrollTop = 0;
export default {
  name: "OrderIndex",
  components: {
    loadingStatusTem,
    MySmallTabbar,
    wxOpenWeapp,
    Popup,
    Datetime,
    OpenModal,
    CustomServiceTmp,
    raterCom
  },
  props: [],
  beforeCreate() { },
  data() {
    return {
      customPointName: localStorage.getItem("customPointName"),
      cfrom: global.ckFrom,
      theme: localStorage.getItem("colorName") ? localStorage.getItem("colorName") : 'mb5_default',
      companyAuth: JSON.parse(localStorage.getItem("companyAuth")),
      cfg: JSON.parse(localStorage.getItem("cfg")),
      isLoading: false,
      isLoading1: false,
      showDetail: false,
      type: 1,
      dataInfo: [],
      detailInfo: [],
      tabList: [{
        title: '未开始',
        index: 1,
      }, {
        title: '已完成',
        index: 2,
      }, {
        title: '已取消',
        index: -2,
      }, {
        title: '已过期',
        index: -3,
      }],
      userListType: 1,
      identity: 1,
      cancelBookingFalg: false,
      aeId: '',
      sureBookingShowFalg: false,
      sureTime: '',
      dataStatus: 'HAS_MORE_DATA',
      sAtId: 0,
      showEnterPcTip:false,
      pcUrl:'',
      teacherWxappQuery:'',
      bookingTypeList: [{
        title: '我的排班',
        index: 1,
      }, {
        title: '我的预约',
        index: 2,
      }],
      typeBar: 1,
      schedulingList: [],
      schedulingDataStatus: 'HAS_MORE_DATA',
      bookingInfoOnly: false,
      isFromOrder: 0,
      popUploadSummarize: false,
      textContent: '',
      uploadImgList: [],
      isWeiXin: true,
      cancelBtnSetting: true,
      commentList: [],
      goodTemplates: [],
      badTemplates: [],
      showComment: false,
      commentText: '',
      rate: 0,
      commentItem: null, // 当前操作对象
      vipType: localStorage.getItem("vipType" + localStorage.getItem("userId")),
    };
  },
  created() {
    utilJs.appShare(this);
  },
  mounted() {
  },
  computed: {},
  watch: {
    $route(to, from) {
      // 新增课程可以关联课程后，可能会从出现从视频详情页跳入视频详情页的情况，无法进入activate
      if (to.path == '/member/myBooking/myBookingList' && from.path == '/member/myBooking/myBookingList') {
        this.initData();
      }
    },
    rate(val, oldVal) {
      if (val == 5) {
        for (let val of this.badTemplates) {
          val.isChoosed = false;
        }
        this.choosedBadTemp = '';
        this.commentText = '';
      } else if (oldVal == 5 && (val == 1 || val == 2 || val == 3 || val == 4)) {
        for (let val of this.goodTemplates) {
          val.isChoosed = false;
        }
        this.choosedGoodTemp = '';
        this.commentText = '';
      }
    }
  },
  methods: {
    checkSubmit() {
      if (
        this.textContent == "" &&
        this.uploadImgList.length == 0
      ) {
        this.$showCjToast({
          text: "请提交内容",
          type: "warn",
        });
        return false;
      } else if (this.textContent.length > 1000) {
        this.$showCjToast({
          text: "字数最多为1000字",
          type: "warn",
        });
        return false;
      } else {
         return true;
      }
    },
    submitSummary() {
      if (!this.checkSubmit()) {
        return;
      }
      if (this.isLoading) {
        return;
      }
      this.isLoading = true;
      let postUrl = `${global.apiurl}appointment/summary`
      let imgs = [];
      if (this.uploadImgList.length > 0) {
        for (let i = 0; i < this.uploadImgList.length; i++) {
          imgs.push(this.uploadImgList[i].url)
        }
      }
      let postData = {
        aeId: this.aeId,
        content: this.textContent,
        imgs: imgs
      }
      utilJs.postMethod(
        postUrl,
        postData,
        (res) => {
          this.isLoading = false;
          this.popUploadSummarize = false;
          this.$showCjToast({
            text: "提交成功",
            type: "success",
          });
        },
        (failRes) => {
          this.isLoading = false;
        }
      );
    },
    //点击添加图片
    clickAnswerPic(event) {
      if (this.uploadImgList.length >= 5) {
        this.$showCjToast({
          text: "图片最多只能传5张",
          type: "warn",
        });
        return;
      }
      if (this.isWeiXin) {
        wxUtilJs
          .chooseImage({
            count: 5, // 默认9
            sizeType: ["compressed"], //可以指定是原图还是压缩图，默认二者都有
            sourceType: ["album", "camera"] // 可以指定来源是相册还是相机，默认二者都有
          })
          .then((localIds) => {
            this.$loading.show({
              text: "上传中..."
            });
            serverIdImgArr = [];
            //获取剩余能传多少张图片，若已选的图片数量大于剩余数。则只传剩余数量的图片
            let residueLength = 5 - this.uploadImgList.length;
            if (localIds.length > residueLength) {
              localIds.length = residueLength;
            }
            this.wxUploadImg(localIds, localIds.length - 1);
          });
      } else {
        utilJs.imgUpload(
          event.target.files,
          imgData,
          "clock",
          (res) => {
            let urlObj = {
              url: res
            };
            this.uploadImgList.push(urlObj);
          },
          (fRes) => {}
        );
      }
    },
    //上传图片到微信-----IOS不能一次性传多张，只好递归传
    wxUploadImg(localIds, localIdsLength) {
      wxUtilJs
        .uploadImage(
        {
          localId: localIds[localIdsLength]
        },
          true
        )
        .then((res) => {
          serverIdImgArr.push(res);
          if (localIdsLength > 0) {
            this.wxUploadImg(localIds, --localIdsLength);
          } else {
            this.syncUploadPic(serverIdImgArr);
          }
        });
    },

    //上传图片到服务器
    syncUploadPic(serverIdArr) {
      utilJs.postMethod(
        global.apiurl + "signCard/downWxImg ",
        {
          serverId: JSON.stringify(serverIdArr),
          mediaType: 2
        },
        (res) => {
          this.$loading.hide();
          for (let key of res) {
            if (this.uploadImgList.length >= 9) {
              break;
            }
            let urlObj = {
              url: key
            };
            this.uploadImgList.push(urlObj);
          }
        },
        (failRes) => {
          this.$loading.hide();
        }
      );
    },
    //删除上传的图片
    delUploadImage(index) {
      this.uploadImgList.splice(index, 1);
    },

    //点击图片放大预览
    clickPreviewImage(imgUrl) {
      if (!imgUrl) {
        return;
      }
      let imgArr = [];
      for (let key of this.uploadImgList) {
        imgArr.push(key.url);
      }
      let imgData = {
        current: imgUrl, // 当前显示图片的http链接
        urls: imgArr
      }
      wxUtilJs.previewImage(imgData)
      // wxUtilJs.previewImage({
      //   current: imgUrl, // 当前显示图片的http链接
      //   urls: imgArr // 需要预览的图片http链接列表
      // });
    },
    uploadSummarize(id) {
      this.uploadImgList = [];
      this.textContent = "";
      this.aeId = id;
      let getUrl = `${global.apiurl}appointment/getSummary?aeId=${this.aeId}`;
      // if (this.textContent == '' && this.uploadImgList.length == 0) {
      utilJs.getMethod(getUrl, (res) => {
        if (res && JSON.stringify(res) != '[]') {
          this.textContent = res.content;
          if (res.imgs && res.imgs.length > 0) {
            for (let i = 0; i < res.imgs.length; i++) {
              this.uploadImgList.push({url: res.imgs[i]})
            }
          }
        }
        this.popUploadSummarize = true;
      }, failRes => {
        this.popUploadSummarize = true;
      })
      // } else {
      //   this.popUploadSummarize = true;
      // }
    },
    goMyScheduling(atId) {
      this.$routerGo(this, "push", {
        path: "/homePage/booking/bookingTime",
        query: {
          atId: atId,
          ckFrom: global.ckFrom.booking,
          isFromScheduling: true
        }
      });
    },
    goStudentList(atId) {
      this.$routerGo(this, "push", {
        path: `/member/myBooking/myBookingList`,
        query: {
          userListType: 2,
          sAtId: atId
        }
      });
    },
    getSchedulingList() {
      if (!this.isLoading) {
        this.isLoading = true;
        let $this = this;
        this.$loading.show();
        utilJs.getMethod(
          global.apiurl + `appointment/schedulingList?&page=${schedulingPage}&limit=${LIMIT}`,
          function (res) {
            $this.$loading.hide();
            if (schedulingPage == 1) {
              if (res.data && res.data.length == 0) { //不是老师，直接跳转到学员预约列表
                $this.$routerGo($this, "replace", {
                  path: `/member/myBooking/myBookingList`,
                  query: {
                    userListType: 1
                  }
                });
              }
              $this.schedulingList = res.data;
            } else {
              $this.schedulingList = [...$this.schedulingList, ...res.data];
            }
            if (res.data && (res.data.length < LIMIT)) {
              $this.schedulingDataStatus = schedulingPage == 1 && res.data.length == 0 ? 'NO_DATA' : 'NO_MORE_DATA';
            } else {
              $this.schedulingDataStatus = 'HAS_MORE_DATA';
              page++;
            }
            $this.isLoading = false;
          }, function () {
            $this.schedulingDataStatus = 'DATA_ERROR';
            $this.$loading.hide();
            $this.isLoading = false;
          }
        );
      }
    },
    changeBookingType(type) {
      if (type == this.typeBar)
        return;
      this.typeBar = type;
      if (type == 1) {
        this.schedulingList = [];
        schedulingPage = 1;
        this.schedulingDataStatus = 'HAS_MORE_DATA';
        this.getSchedulingList();
      } else {
        this.dataInfo = [];
        page = 1;
        this.type = 1;
        this.dataStatus = 'HAS_MORE_DATA';
        this.getBookingList();
      }
    },
    clickRestartBook(liveId) {
      this.$cjConfirm({
        title: '提示',
        titleCenter: true,
        message: '确定要重新开启咨询吗，重新开启后，咨询时间将延长1小时',
        messageCenter: true,
        showMasker: true,
        clickCloseModal: false,
        showCancelButton: true,
        cancelButtonText: '取消',
        confirmButtonText: '确定',
        onConfirm:() => {
         utilJs.postMethod(`${global.apiurl}live/appointmentLive/resetLiveTime/${liveId}`, {}, (res) => {
            this.$showCjToast({
              text: '开启成功',
              type: 'success'
            });
            page = 1;
            this.getBookingList();
         })
        },
      })

    },
    clickShowLiveQrcode(atmId) {
      utilJs.getMethod(`${global.apiurl}live/appointmentLive/getLiveRoomUrl/${atmId}`, (res) => {
        this.pcUrl = res.pcUrl;
        const ENV = process.env.VUE_APP_ENV;
        const ENV_MAP = {
          'dev':1,
          'sit':2,
          'production':3
        };
        this.teacherWxappQuery = `env=${ENV_MAP[ENV]}&liveId=${res.liveId}&userId=${localStorage.getItem("userId")}`;
        this.showEnterPcTip = true;
      })
    },
    copyText() {
      utilJs.copyText(this.pcUrl);
    },
    sureBookingShow(id) {
      this.sureBookingShowFalg = true
      this.aeId = id
      this.sureTime = ''
    },
    sureBooking() {
      if (!clickFlag) {
        return
      }
      let $this = this
      clickFlag = true
      let data = {
        aeId: this.aeId
      }
      if (this.type == -3) {
        data.consumptionAt = this.sureTime
      }
      utilJs.postMethod(`${global.apiurl}appointment/confirmHandle`, data, function (res) {
        $this.sureBookingShowFalg = false
        clickFlag = true
        page = 1
        $this.getBookingList();
      },
        failRes => {
          $this.sureBookingShowFalg = false
          clickFlag = true
        });
    },
    cancelBookingShow(id) {
      this.cancelBookingFalg = true
      this.aeId = id
    },
    cancelBooking() {
      if (!clickFlag) {
        return
      }
      let $this = this
      clickFlag = false
      utilJs.postMethod(`${global.apiurl}appointment/cancelHandle`, {aeId: this.aeId, operatorType: this.userListType == 1 ? 1 : 2}, function (res) {
        $this.$showCjToast({
          text: "取消成功",
          type: "success"
        });
        $this.cancelBookingFalg = false;
        clickFlag = true
        page = 1
        $this.getBookingList();
      },
        failRes => {
          $this.cancelBookingFalg = false;
          clickFlag = true
        });
    },
    getDetail(i) {
      let item = this.dataInfo[i];
      utilJs.getMethod(`${global.apiurl}appointment/getEnrollDetail?aeId=${item.aeId}&type=${this.userListType}`, res => {
        if (res.remark && res.remark.length > 0 && Array.isArray(res.remark)) {
          for (let i = 0; i < res.remark.length; i++) {
            if (res.remark[i].type == 1 && res.remark[i].content && res.remark[i].content.substr(0, 4) == 'http' && res.remark[i].content.length > 5) {
              let ic = res.remark[i].content;
              res.remark[i].content = '';
              utilJs.getPageHtml(ic, sres => {
                res.remark[i].content = sres;
              })
            }
          }
        }
        this.detailInfo = res;
        this.showDetail = true;
        document.body.style.overflow = 'hidden';
        this.$nextTick(() => {
          this.$refs.box.scrollTo(0, 0)
        })
      }, failRes => {
      });
    },
    onHide() {
      document.body.style.overflow = '';
    },
    closeDetail() {
      this.showDetail = false;
      document.body.style.overflow = '';
    },
    changeType: function (type) {
      this.dataInfo = [];
      page = 1;
      this.type = type;
      this.getBookingList();
    },
    clickChangeRole() {
      if (this.userListType == 1) {
        this.userListType = 2
      } else {
        this.userListType = 1
      }
      page = 1
      this.getBookingList()
    },
    // 预约列表
    getBookingList() {
      if (!this.isLoading1) {
        this.isLoading1 = true;
        this.$loading.show();
        let getUrl = '';
        if (this.userListType == 2) {
          getUrl = global.apiurl + `appointment/getEnrollByUser?status=${this.type}&type=${this.userListType}&page=${page}&limit=${LIMIT}&atId=${this.sAtId}`
        } else {
          getUrl = global.apiurl + `appointment/getEnrollByUser?status=${this.type}&type=${this.userListType}&page=${page}&limit=${LIMIT}`
        }
        utilJs.getMethod(getUrl, (res) => {
            this.$loading.hide();
            this.userListType = res.type//列表类型 【1 学员，2 老师】
            this.identity = res.identity//用户身份【1 学员，2 老师】（老师身份 可以切换身份，可以确认消费，取消预约；学员身份可以 评论）
            this.cancelBtnSetting = res.setting && res.setting.cancelButton == 1 ? true : false
            if (res.setting) {
              this.cancelBtnSetting = res.setting.cancelButton == 1 ? true : false
            }
            let list = [];
            if (page == 1) {
              list = res.data.data;
            } else {
              list = [...this.dataInfo, ...res.data.data];
            }
            if (res.data.data && (res.data.data.length < LIMIT)) {
              this.dataStatus = page == 1 && res.data.data.length == 0 ? 'NO_DATA' : 'NO_MORE_DATA';
            } else {
              this.dataStatus = 'HAS_MORE_DATA';
              page++;
            }
            this.isLoading1 = false;
            const ENV = process.env.VUE_APP_ENV;
            const ENV_MAP = {
              'dev':1,
              'sit':2,
              'production':3
            }
            list.forEach((item, index) => {
              if (item.consumptionPattern == 4) {
                item.wxappQuery = `env=${ENV_MAP[ENV]}&liveId=${item.liveId}&userId=${localStorage.getItem("userId")}`
              }
            })
            this.dataInfo = list;
          }, function () {
            this.dataStatus = 'DATA_ERROR';
            this.$loading.hide();
            this.isLoading1 = false;
          }
        );
      }
    },
    // 去评论
    goComment(item) {
      this.commentItem = item;
      this.showComment = true;
      this.commentText = '';
      this.rate = 0;
      this.getTemplate();
    },
    //IOS微信6.7以上版本会导致输入法收起的时候，键盘没收起，需要手动滚下屏幕
    inputFocus() {
      if (navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)) {
        inputScrollTop = document.documentElement.scrollTop || document.body.scrollTop;
      }
    },
    inputBlur() {
      if (navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)) {
        setTimeout(() => {
          document.body.scrollTop = inputScrollTop - 1 || 0;
        });
      }
    },
    // 获取评论模板
    getTemplate() {
      if (!this.isLoading) {
        this.isLoading = true;
        let $this = this;
        utilJs.getMethod(`${global.apiurl}commentTemplate?prodType=86&levels[]=1&levels[]=2`, res => {
          $this.isLoading = false;
          $this.goodTemplates = res[0].comments;
          $this.badTemplates = res[1].comments;
          let tagList = [];
          for (let key of $this.goodTemplates) {
            let isChoosed = false;
            let item = {
              content: key.content,
              ctId: key.ctId,
              isChoosed: isChoosed
            }
            tagList.push(item);
          };
          $this.goodTemplates = tagList;
          let tagList1 = [];
          for (let key of $this.badTemplates) {
            let isChoosed = false;
            let item = {
              content: key.content,
              ctId: key.ctId,
              isChoosed: isChoosed
            }
            tagList1.push(item);
          };
          $this.badTemplates = tagList1;
        }, failRes => {
          $this.isLoading = false;
        });
      }
    },
    // 选择评论模板
    chooseTag(content, i, isChoosed, type) {
      this.type = type;

      if (type == 1) {
        this.goodTemplates[i].isChoosed = !isChoosed;
        if (this.goodTemplates[i].isChoosed) {
          if (this.commentText == "") {
            this.commentText = content;
          } else {
            this.commentText = this.commentText + "," + content;
          }
        } else {
          if (this.commentText.indexOf("," + content) > -1) {
            this.commentText = this.commentText.replace("," + content, "");
          } else {
            this.commentText = this.commentText.replace(content, "");
          }
        }
      } else {
        this.badTemplates[i].isChoosed = !isChoosed;
        if (this.badTemplates[i].isChoosed) {
          if (this.commentText == "") {
            this.commentText = content;
          } else {
            this.commentText = this.commentText + "," + content;
          }
        } else {
          if (this.commentText.indexOf("," + content) > -1) {
            this.commentText = this.commentText.replace("," + content, "");
          } else {
            this.commentText = this.commentText.replace(content, "");
          }
        }
      }
    },
    // 提交评论
    submitComment() {
      if (this.isLoading) {
        return;
      }
      if (this.rate == 0) {
        this.$showCjToast({
          text: "请完成评分",
          type: "warn",
        });
        return;
      }
      let data = {
        atId: this.commentItem.atId,
        aeId: this.commentItem.aeId,
        score: Number(this.rate * 2),
        content: this.commentText
      };
      this.isLoading = true;
      utilJs.postMethod(`${global.apiurl}appointment/createComment`, data, res => {
        this.isLoading = false;
        page = 1
        this.getBookingList()
        this.showComment = false;
        if (res.isBan == 1) {
          this.$cjConfirm({
            showCancelButton: false,
            title: '温馨提示',
            message: `暂无权限评论，请联系管理员~`,
          });
          return
        }
        this.$showCjToast({
          text: "评论成功",
          type: "success"
        });
      },
        failRes => {
          this.isLoading = false;
        });
    },
    hideComment() {
      this.showComment = false;
    },
    //分享
    wechatShare: function () {
       utilJs.wechatConfig('', "", "", "", function () { }, true, {
          isWxOpenLaunchWeap: 1,
        });
      // let shareUrl =
      //   window.location.href.split("#")[0] +
      //   "#" +
      //   this.$route.path +
      //   "?refereeId=" +
      //   localStorage.getItem("userId");
      // utilJs.wechatConfig(shareUrl, "我的预约", "", "", function () { }, true, {
      //     isWxOpenLaunchWeap: 1,
      //   });
    },
    //手机端分享
    appShare: function () {
      utilJs.appShareTrue("", "", "", "");
      // let shareUrl =
      //   window.location.href.split("#")[0] +
      //   "#" +
      //   this.$route.path +
      //   "?refereeId=" +
      //   localStorage.getItem("userId");
      // utilJs.appShareTrue("我的预约", "", shareUrl, "");
    },
    windowScrollFunction: function () {
      let that = this;
      utilJs.handleLoading(function () {
        if (that.dataStatus == 'HAS_MORE_DATA' && that.dataInfo.length > 0 && ( that.typeBar == 2 || that.bookingInfoOnly)) {
          that.getBookingList();
        }
        if (that.schedulingDataStatus == 'HAS_MORE_DATA' && that.schedulingList.length > 0 && that.typeBar == 1) {
          that.getSchedulingList();
        }
      });
    },
    onVisibilityChangeEvent() {
      //页面切回来刷新
        if (document.visibilityState === 'visible' && this.dataInfo.length) {
          page = 1;
          this.getBookingList();
        }
    },
    initData() {
      this.dataInfo = [];
      this.detailInfo = [];
      this.isLoading = false;
      this.isLoading1 = false;
      this.showDetail = false;
      this.type = 1;
      this.userListType = this.$route.query.userListType;
      this.sAtId = this.$route.query.sAtId || 0;
      this.isFromOrder = this.$route.query.isFromOrder || 0;
      this.popUploadSummarize = false;
      this.textContent = '';
      this.uploadImgList = [];
      this.serverIdImgArr = [];
      this.aeId = '';
      page = 1
      this.bookingTypeList = [{
        title: '我的排班',
        index: 1,
      }, {
        title: '我的预约',
        index: 2,
      }];
      this.typeBar = this.isFromOrder == 1 ? 2 : 1;
      this.schedulingList = [];
      this.schedulingDataStatus = 'HAS_MORE_DATA';
      this.cancelBtnSetting = true;
      this.commentItem = null;
      if (this.isFromOrder == 1) { //购买完成后
        setDocumentTitle("我的预约");// eslint-disable-line
        this.bookingInfoOnly = false;
        this.userListType = 1;
        this.getSchedulingList();
        this.getBookingList();
      } else if (this.$route.query.userListType && (this.$route.query.userListType == 1 || this.$route.query.userListType == 2)) {
        //学员身份（可能是老师作为学员），或者老师（作为老师）查看自己底下的学员预约
        if (this.userListType == 1) {
          setDocumentTitle("我的预约");// eslint-disable-line
        } else {
          setDocumentTitle("学员预约");// eslint-disable-line
        }
        this.bookingInfoOnly = true;
        this.getBookingList();
      } else {
        setDocumentTitle("我的排班");// eslint-disable-line
        //从个人中心进入页面，先展示老师身份，不是老师身份再跳转学员身份
        this.bookingInfoOnly = false;
        this.userListType = 1;
        this.getSchedulingList();
      }
    }
  },
  activated() {
    this.initData();
    this.isWeiXin = utilJs.isWeiXin() && utilJs.isMobileUserAgent();
    //获取阿里云签名，除了微信浏览器以外
    if (!this.isWeiXin) {
      utilJs.getAliSign(`${global.apiurl}imageSign`, (res) => {
        imgData = res;
      });
    }
    window.addEventListener('scroll', this.windowScrollFunction);
    document.addEventListener('visibilitychange', this.onVisibilityChangeEvent);
    this.wechatShare();
  },
  deactivated() {
    this.loadingStatus = 'NO_MORE_DATA';
    window.removeEventListener('scroll', this.windowScrollFunction);
    document.removeEventListener('visibilitychange', this.onVisibilityChangeEvent);
  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.invite-book-bg-img{
  width: 11.5rem;
  height: 14.55rem;
  background-image: url('https://ck-bkt-knowledge-payment.oss-cn-hangzhou.aliyuncs.com/admin/material/9_material_admin/image/assets/i/wap/booking/invite_book_dialog_bg3.png');
  background-repeat: no-repeat;
  background-size: 100%;
}
.changeRole {
  position: fixed;
  bottom: 1rem;
  right: 0;
  box-shadow: 0 2px 4px 0 rgba(254,121,0,0.30);
  border-radius: 2.5rem 0 0 2.5rem;
}
.sureTime >>> .vux-datetime-value {
  text-align: left;
  padding-left: 0.4rem!important;
}
.closeBig >>> p > img,
.closeBig >>> section > img,
.closeBig >>> div > img,
.closeBig >>> img {
  pointer-events: none;
  -webkit-user-select: none;
  -moz-user-select: none;
  -webkit-user-select: none;
  -o-user-select: none;
  user-select: none;
}
.aCloseBig >>> p > a > img,
.aCloseBig >>> section > a > img,
.aCloseBig >>> div > a > img {
  pointer-events: none;
  -webkit-user-select: none;
  -moz-user-select: none;
  -webkit-user-select: none;
  -o-user-select: none;
  user-select: none;
}
.c-p-t144{
  top: 3.6rem;
}
.c-mh12 {
  margin-left: 0.3rem;
  margin-right: 0.3rem;
}
.theme-back {
  background: #5491FF !important;
}
.textarea {
  background: #F9FAF9;
  border: 1px solid #F2F3F2;
}
</style>
